import re, random, json

from ronglian_sms_sdk import SmsSDK
from flask import current_app
from application import status, message, redis


class SMS():
    """短信接口"""

    @property
    def sms(self):
        """接口操实例对象"""
        sdk = SmsSDK(
            current_app.config.get("SMS_ACCOUNT_ID"),
            current_app.config.get("SMS_ACCOUNT_TOKEN"),
            current_app.config.get("SMS_APP_ID")
        )
        return sdk

    def code(self, mobile):
        """发送短信验证码"""
        # 验证手机
        if not re.match("^1[3-9]\d{9}$", mobile):
            return {
                "errno": status.CODE_VALIDATE_ERROR,
                "errmsg": message.mobile_format_error
            }

        # 查询当前手机号是否在冷却时间内曾经发送过短信
        ret = redis.get("int_%s" % mobile)
        if ret is not None:
            return {"errno": status.CODE_INTERVAL_TIME, "errmsg": message.sms_interval_time}

        # 生成验证码
        sms_code = "%06d" % random.randint(0, 999999)
        try:
            from mycelery.sms.tasks import send_sms
            send_sms.delay(mobile, sms_code)  # 立刻调用
            # send_sms.apply_async( # 延时调用,countdown表示延时执行的时间
            #     kwargs={
            #         "mobile": mobile,
            #         "sms_code": sms_code
            #     },
            #     countdown=10,
            #     retry=True
            # )
            # 返回结果
            return {"errno": status.CODE_OK, "errmsg": message.ok}
        except:
            return {"errno": status.CODE_SMS_FAIL, "errmsg": message.sms_send_error}